<template>
  <el-table
    v-loading="loading"
    :data="tableData"
    border
    fit
    highlight-current-row
    height="170"
    size="mini"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    @row-dblclick="rowDblclick"
    @cell-click="cellClick"
  >
    <el-table-column label=" 操作" align="center" fixed width="80">
      <template slot-scope="scope">
        <el-button type="text" size="mini" @click="removeObj(scope.$index)">
          移除
        </el-button>
      </template>
    </el-table-column>
    <template v-for="(th, key) in tableHeader">
      <el-table-column
        v-if="th.prop === 'calc_type'"
        :key="key"
        :prop="th.prop"
        :label="th.label"
        :fixed="th.fixed"
        :min-width="th.minWidth"
        align="center"
        width="150"
      >
        <template slot-scope="scope">
          <span v-if="true">{{ scope.row['lable'] }}</span>
          <span v-if="false" size="mini">{{ scope.row[th.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column
        v-else-if="th.type === 'input'"
        :key="key"
        :prop="th.prop"
        :label="th.label"
        :fixed="th.fixed"
        :min-width="th.minWidth"
        align="center"
        width="150"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row[th.prop]" size="mini"/>
        </template>
      </el-table-column>

      <el-table-column
        v-else-if="th.prop === 'in_stream_name' || th.prop === 'replace_field_by_string' || th.prop === 'field_a' || th.prop === 'field_b' || th.prop === 'field_c' || th.prop === 'name' || th.prop ==='column_name'"
        :key="key"
        :prop="th.prop"
        :label="th.label"
        :fixed="th.fixed"
        :min-width="th.minWidth"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row[th.prop]" size="mini" style="width: 100%;" @focus="getFiledsOptions">
            <el-option
              v-for="item in fieldsOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column
        v-else-if="th.prop === 'format' || th.prop === 'conversion_mask'"
        :key="key"
        :prop="th.prop"
        :label="th.label"
        :fixed="th.fixed"
        :min-width="th.minWidth"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row[th.prop]" size="mini" style="width: 100%;" @focus="getValueFormats(scope.row.type)">
            <el-option
              v-for="item in formatOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column
          v-else-if="th.prop === 'aggregate_type'"
          :key="key"
          :prop="th.prop"
          :label="th.label"
          :fixed="th.fixed"
          :min-width="th.minWidth"
          align="center"
          width="200"
      >
        <template slot-scope="scope">
          <el-select  v-model="scope.row[th.prop]" placeholder="请选择聚合类型" style="width:100%">
            <el-option
                v-for="item in typeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        v-else-if="th.type === 'select'"
        :key="key"
        :prop="th.prop"
        :label="th.label"
        :fixed="th.fixed"
        :min-width="th.minWidth"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row[th.prop]" size="mini" style="width: 100%;">
            <el-option
              v-for="item in options[key]"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>
    </template>
    <el-dialog
      :visible.sync="calcTypevisible"
      :close-on-click-modal="false"
      :title="calcTypeDialogTitle"
      width="40%"
      :append-to-body="true"
    >
      <span>选择计算模型来执行</span>
      <el-table
        :data="calcType"
        border
        height="300px"
        highlight-current-row
        @current-change="currentChange"
        @row-dblclick="rowDbclick"
      >
        <el-table-column property="name" label="计算模型"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="calcTypevisible = false">取消</el-button>
      </span>
    </el-dialog>
  </el-table>
</template>

<script>
/* eslint semi: ["error", "always"] */
import API from '../../../../../api/index';
export default {
  name: 'TableFields',
  props: {
    tableData: {
      type: Array,
      default: function() {
        return [];
      }
    },
    rowDblclick: {
      type: Function,
      default: (row, event, column) => {}
    },
    tableHeader: {
      type: Array,
      default: function() {
        return [];
      }
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableFiledData: [],
      calcTypevisible: false,
      calcTypeDialogTitle: '选择计算类型',
      calcType: [],
      currentData: null,
      currentRow: null,
      typeOptions: [],
      fieldsOptions: [],
      options: [],
      key: '',
      label: '',
      value: '',
      filedIndex: 0,
      formatOptions: [],
      typeList: [{ code: 'SUM', name: 'SUM' },
        { code: 'MIN', name: 'MIN' },
        { code: 'MAX', name: 'MAX' },
        { code: 'AVG', name: 'AVG' },
        { code: 'COUNT', name: 'COUNT' }
      ]
    };
  },
  mounted() {
    this.getOptiones();
  },
  methods: {
    cellClick(row, column, cell, event) {
      if (column.property === 'calc_type') {
        API.studio.calculator().then(res => {
          this.$set(this, 'calcType', res.data);
        });
        this.calcTypevisible = true;
        this.currentRow = row;
      }
    },
    removeObj(index) {
      this.$emit('removeObj', index);
    },
    getFiledsOptions() {
      if (this.fieldsOptions) {
        this.$emit('getStreamFieldOptions');
      }
    },
    getValueFormats(param) {
      if (param) {
        API.studio.valueFormats({ 'valueMetaName': param }).then(res => {
          this.formatOptions = res.data;
        });
      } else {
        this.formatOptions = [];
      }
    },
    currentChange(currentRow, oldCurrentRow) {
      this.currentData = currentRow;
    },
    rowDbclick(row) {
      this.$set(this.currentRow, 'calc_type', row.code);
      this.$set(this.currentRow, 'lable', row.name);
      this.calcTypevisible = false;
    },
    handleSubmit() {
      if (this.currentData) {
        this.$set(this.currentRow, 'lable', this.currentData.name);
        this.$set(this.currentRow, 'calc_type', this.currentData.code);
      }
      this.calcTypevisible = false;
    },
    setOptions(result) {
      if (result) {
        if (this.fieldsOptions.length === 0) {
          var tempFileds = [];
          result.data.data.data.fields.forEach(element => {
            const obj = {};
            obj.name = element.name;
            tempFileds.push(obj);
          });
          this.fieldsOptions = tempFileds;
        }
      }
    },
    async getOptiones() {
      const tempOption = [];
      for (let index = 0; index < this.tableHeader.length; index++) {
        tempOption[index] = [];
        const element = this.tableHeader[index];
        const key = element['prop'];
        if (key === 'type' || key === 'value_type') {
          await API.studio.valueMetas().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'encoding') {
          await API.studio.encodings().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'set_empty_string' || key === 'idrem' || key === 'use_regex' || key === 'whole_word' || key === 'case_sensitive' || key === 'repeat' || key === 'date_format_lenient' || key === 'lenient_string_to_number' || key === 'binary_to_normal' || key === 'init_cap' || key === 'null_allowed' || key === 'is_trim') {
          tempOption[index] = [{ code: 'Y', name: '是' }, { code: 'N', name: '否' }];
        } else if (key === 'fieldType') {
          tempOption[index] = [{ code: 'NUMBER', name: 'NUMBER' }, { code: 'STRING', name: 'STRING' },{ code: 'DATE', name: 'DATE' }];
        } else if (key === 'trimtype') {
          await API.studio.trimTypes().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'comparators') {
          await API.studio.comparators().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'is_lower') {
          tempOption[index] = [{ code: 'none', name: '不操作' }, { code: 'lower', name: '转换小写' }, { code: 'upper', name: '转换大写' }];
        } else if (key === 'digits') {
          await API.studio.digits().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'padding_type') {
          await API.studio.paddings().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'remove_special_character') {
          await API.studio.specialCharacters().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'escape') {
          await API.studio.escapeMasks().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'date_format_timezone') {
          await API.studio.timezones().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'date_format_locale') {
          await API.studio.locales().then(res => {
            tempOption[index] = res.data;
          });
        } else if (key === 'element_type') {
          tempOption[index] = [{ code: 'node', name: '节点' }, { code: 'prop', name: '属性' }];
        } else if (key === 'result_type') {
          tempOption[index] = [{ code: 'value', name: 'Value of' }, { code: 'single', name: 'Single node' }];
        } else if (key === 'content_type') {
          tempOption[index] = [{ code: 'Attribute', name: 'Attribute' }, { code: 'Element', name: 'Element' }];
        } else {
          tempOption[index] = [];
        }
      }
      this.$set(this, 'options', tempOption);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>
